package com.wang.server.netty.handler;

import com.alibaba.fastjson.JSON;
import com.wang.rest.RestServer;
import com.wang.utils.DatabaseUtils;
import io.netty.buffer.Unpooled;
import io.netty.channel.*;
import io.netty.handler.codec.http.*;
import io.netty.util.CharsetUtil;

import java.sql.Connection;
import java.sql.ResultSet;

//自定义的ChannelHandler
@ChannelHandler.Sharable
public class RestfulServerHandler extends SimpleChannelInboundHandler<FullHttpRequest> {
    private RestServer server = null;
    private String prefix = "";
    private Connection conn = null;

    public RestfulServerHandler() {

    }

    public RestfulServerHandler(String prefix, Connection conn) {
        this.prefix = prefix;
        this.conn = conn;
    }

    protected void channelRead0(ChannelHandlerContext ctx, FullHttpRequest request) throws Exception {
        System.out.println(request.refCnt());
        String url = request.uri().substring(this.prefix.length());
        String method = request.method().name().toLowerCase();
        String body = request.content().toString(CharsetUtil.UTF_8);
//        request.retain();
//        String sql = server.map(url, method, body);
        String sql = "";
        Object rsp = null;
        if (method.equals("get")) {
            ResultSet rs = conn.createStatement().executeQuery(sql);
            rsp = DatabaseUtils.INSTANCE.map(rs);
        } else if (method.equals("put")) {
            rsp = conn.createStatement().executeUpdate(sql);
        } else {
            rsp = conn.createStatement().execute(sql);
        }
        ctx.fireChannelRead(rsp);
        System.out.println(request.refCnt());
    }
}
